package com.hzit.search.listener;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.domain.Item;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Component
@RabbitListener(queues = "goodsAudit")
public class MyItemListener {

	@Autowired
	private ElasticsearchClient client;

	@RabbitHandler
	public void getMessage(String msg) throws IOException {
		if(StringUtils.isNotBlank(msg)){
			//1. 将接受到的数据转换为List集合
			List<Item> itemList = JSON.parseArray(msg, Item.class);
			//2. 将上面的集合数据放到es中
			BulkRequest.Builder br = new BulkRequest.Builder();
			//3. 遍历数据
			for (Item item : itemList) {
				br.operations(op -> op.index(idx ->
						idx.index("item")
						.id(item.getId() + "")
						.document(item)
				));
			}
			//4. 批量添加
			BulkRequest request = br.build();
			client.bulk(request);
		}
	}
}
